import React, { useState, useEffect } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Button,
  Typography,
  message,
  Space,
} from 'antd';
import {
  TeamOutlined,
  ArrowLeftOutlined,
} from '@ant-design/icons';
import { Link, useNavigate, useSearchParams } from 'react-router-dom';
import { createTopic, getForumSections } from '../../api/forum';
import { ForumSection } from '../../types';

const { Title, Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;

const ForumTopicCreate: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [sectionsLoading, setSectionsLoading] = useState(false);
  const [sections, setSections] = useState<ForumSection[]>([]);
  const [form] = Form.useForm();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams();

  useEffect(() => {
    fetchSections();
  }, []);

  useEffect(() => {
    // 如果URL中有section参数，自动选择该板块
    const sectionParam = searchParams.get('section');
    if (sectionParam && sections.length > 0) {
      form.setFieldsValue({
        sectionId: Number(sectionParam)
      });
    }
  }, [sections, searchParams, form]);

  const fetchSections = async () => {
    try {
      setSectionsLoading(true);
      const response = await getForumSections();
      if (response.code === 200) {
        setSections(response.data);
      }
    } catch (error) {
      console.error('获取版块列表失败:', error);
      message.error('获取版块列表失败');
    } finally {
      setSectionsLoading(false);
    }
  };

  const onFinish = async (values: any) => {
    setLoading(true);
    try {
      const response = await createTopic(values);
      if (response.code === 200) {
        message.success('主题发表成功！');
        // 跳转到对应板块的主题列表
        navigate(`/forum/sections/${values.sectionId}`);
      } else {
        message.error(response.message || '发表失败');
      }
    } catch (error: any) {
      console.error('发表主题失败:', error);
      if (error.response?.data?.message) {
        message.error(error.response.data.message);
      } else {
        message.error('发表失败，请稍后重试');
      }
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <Card>
        <Space direction="vertical" size="large" style={{ width: '100%' }}>
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
            <Title level={2} style={{ margin: 0 }}>
              <TeamOutlined style={{ color: '#1890ff', marginRight: 8 }} />
              发表帖子
            </Title>
            <Link to="/forum">
              <Button icon={<ArrowLeftOutlined />}>
                返回论坛
              </Button>
            </Link>
          </div>

          <Text type="secondary">
            在论坛中发表新帖子，与其他用户分享和讨论。
          </Text>

          <Form
            form={form}
            layout="vertical"
            onFinish={onFinish}
          >
            <Form.Item
              label="选择版块"
              name="sectionId"
              rules={[{ required: true, message: '请选择版块' }]}
            >
              <Select 
                placeholder="请选择要发表的版块"
                loading={sectionsLoading}
              >
                {sections.map(section => (
                  <Option key={section.id} value={section.id}>
                    {section.name}
                    {section.description && (
                      <Text type="secondary" style={{ marginLeft: 8 }}>
                        - {section.description}
                      </Text>
                    )}
                  </Option>
                ))}
              </Select>
            </Form.Item>

            <Form.Item
              label="帖子标题"
              name="title"
              rules={[
                { required: true, message: '请输入帖子标题' },
                { min: 5, message: '标题至少5个字符' },
                { max: 100, message: '标题不能超过100个字符' },
              ]}
            >
              <Input placeholder="请输入帖子标题" />
            </Form.Item>

            <Form.Item
              label="帖子内容"
              name="content"
              rules={[
                { required: true, message: '请输入帖子内容' },
                { min: 10, message: '内容至少10个字符' },
                { max: 5000, message: '内容不能超过5000个字符' },
              ]}
            >
              <TextArea
                rows={10}
                placeholder="请输入帖子内容..."
              />
            </Form.Item>

            <Form.Item>
              <Space>
                <Button
                  type="primary"
                  htmlType="submit"
                  loading={loading}
                  size="large"
                >
                  发表帖子
                </Button>
                <Button size="large" onClick={() => navigate('/forum')}>
                  取消
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Space>
      </Card>
    </div>
  );
};

export default ForumTopicCreate; 